<template>
  <div class="analysis3-container">
    <div class="left-container">
      <div
        class="left-item"
        :class="leftIndex === index && 'active'"
        v-for="(item, index) in leftData"
        :key="index"
        @click="leftClick(index)"
      >{{ item.name }}</div>
    </div>
    <div class="right-container">
      <div class="query-container">
        <el-select v-model="queryType" placeholder="请选择" style="margin-right: 30px;" @change="queryModel = null">
          <el-option
            v-for="item in queryTypes"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
        <el-date-picker
          v-if="queryType === '年'"
          v-model="queryModel"
          align="right"
          type="year"
          value-format="yyyy"
          :clearable="false"
          placeholder="选择年份">
        </el-date-picker>
        <el-date-picker
          v-if="queryType === '月'"
          v-model="queryModel"
          align="right"
          type="month"
          value-format="yyyy-MM"
          :clearable="false"
          placeholder="选择月份">
        </el-date-picker>
        <el-date-picker
          v-if="queryType === '日'"
          v-model="queryModel"
          align="right"
          type="date"
          value-format="yyyy-MM-dd"
          :clearable="false"
          placeholder="选择日期">
        </el-date-picker>
        <el-button type="primary" style="margin-left: 30px;" @click="getTopData">查询</el-button>
      </div>
      <div class="top-container">
        <div class="one" ref="oneChart"></div>
        <div class="two" ref="twoChart"></div>
        <div class="three" ref="threeChart"></div>
      </div>
      <div class="bottom-container">
        <div class="oneBottom" ref="oneBottomChart"></div>
        <!-- <div class="twoBottom" ref="twoBottomChart"></div>
        <div class="threeBottom" ref="threeBottomChart"></div>-->
      </div>
    </div>
  </div>
</template>

<script>
import echarts from "echarts";
import moment from "moment";

export default {
  data() {
    return {
      queryTypes: ['年', '月', '日'],
      queryType: '年',
      queryModel: moment().format('YYYY'),
      leftData: [],
      leftIndex: 0,
      topOneChart: null,
      topTwoChart: null,
      topThreeChart: null,
      bottomOneChart: null
    };
  },
  async mounted() {
    await this.getLeftData();
    await this.getTopData();
    await this.getBottomDataQuery();
  },
  methods: {
    async getLeftData() {
      const result = await this.$fetchGet("/common/findAllPowerEnum");
      this.leftData = result.result.supplyPower;
    },
    async getTopData() {
      const obj = {
        storageheat: "储热设备",
        mainSupplyPower: "市电供电",
        powerGeneration: "分布式太阳能",
        supplycool: "空气源热泵",
        shaSupplyHeat: "浅层地源热泵",
        supplyHeat: "燃气锅炉",
        munSupplyHeat: "市政供热",
        storagepower: "储电设备"
      };
      if (!this.queryModel) {
        this.$message.warning('请选择时间')
        return
      }
      let arr = this.queryModel.split('-')
      let title
      if (arr.length === 1) {
        title = arr[0] + '年'
      } else if (arr.length === 2){
        title = arr[0] + '年' + arr[1] + '月'
      } else {
        title = arr[0] + '年' + arr[1] + '月' + arr[2] + '日'
      }
      const result = await this.$fetchGet(
        `/power/getSupplyPowerDtoByPowerTypeAndDate/${this.queryModel}`
      );
      this.topOneChart = echarts.init(this.$refs["oneChart"]);
      const arr1 = [];
      Object.keys(result.result.power).forEach(key => {
        arr1.push({
          name: obj[key],
          value: result.result.power[key]
        });
      });
      this.topOneChart.setOption(this.topOption(title + "电供给占比", arr1));
      this.topTwoChart = echarts.init(this.$refs["twoChart"]);
      const arr2 = [];
      Object.keys(result.result.cool).forEach(key => {
        arr2.push({
          name: obj[key],
          value: result.result.cool[key]
        });
      });
      this.topTwoChart.setOption(this.topOption(title +  "冷供给占比", arr2));
      if (this.topThreeChart) {
        this.topThreeChart.clear()
      }
      this.topThreeChart = echarts.init(this.$refs["threeChart"]);
      const arr3 = [];
      Object.keys(result.result.heat).forEach(key => {
        arr3.push({
          name: obj[key],
          value: result.result.heat[key]
        });
      });
      this.topThreeChart.setOption(this.topOption(title +  "热供给占比", arr3));
    },
    async getBottomDataQuery() {
      const obj = {
        SUNPOWER: { // 分布式太阳能
          powerGeneration: '发电量'
        },
        MAINSPOWER: { // 市电供电
          supplyPower: '供电量'
        },
        STORAGEPOWER: { // 储电设备
          supplyPower: '充电量',
          freePower: '放电量'
        },
        AIRSOURCE: { // 空气源热泵 
          consumePower: '耗电量',
          supplycool: '供冷量',
        },
        FUELBOILER: { // 燃气锅炉
          supplyAir: '耗气量',
          supplyHeat: '供热量'
        },
        SHALLOWLAND: { // 浅层地源热泵
          consumePower: '耗电量',
          supplycool: '制冷量',
          supplyHeat: '供热量'
        },
        STORAGEHEAT: { // 储热设备
          storagePower: '储热量',
          supplyPower: '供热量'
        },
        MUNICIPALHEAT: { // 市政供热
          munSupplyHeat: '供热量'
        }
      };
      const result = await this.$fetchGet(
        `/power/getSupplyPowerDtoByDateType/YEAR/${moment().format("YYYY")}/${
          this.leftData[this.leftIndex].code
        }`
      );
      const arr = [];
      if (result.result) {
        Object.keys(result.result[0]).forEach(key => {
          if (result.result[0][key]) {
            if (obj[this.leftData[this.leftIndex].code][key]) {
              console.log(obj[this.leftData[this.leftIndex].code])
              arr.push({
                name: obj[this.leftData[this.leftIndex].code][key],
                value: result.result[0][key],
                code: key
              });
            }
          }
        });
      }

      this.bottomOneChart = echarts.init(this.$refs["oneBottomChart"]);
      this.bottomOneChart.setOption(
        // 【冷水】月能耗分析
        this.bottomOption(`2020年供能侧分析`, arr)
      );
      this.bottomOneChart.on("click", params => {
        let code;
        Object.keys(obj[this.leftData[this.leftIndex].code]).forEach(key => {
          console.log(obj[this.leftData[this.leftIndex].code][key], params.name)
          if (obj[this.leftData[this.leftIndex].code][key] === params.name) {
            code = key;
          }
        });
        this.getBottomData(code, moment().format("YYYY"));
      });
    },
    async getBottomData(code, date) {
      console.log(code)
      let dateType;
      let dates = date;
      let arr = date.split("-");
      if (arr.length === 1) {
        dateType = "MONTH";
      } else if (arr.length === 2) {
        dateType = "DAY";
        dates = moment(dates).format("YYYY-MM");
      } else if (arr.length === 3) {
        dateType = "HOUR";
        dates = moment(dates).format("YYYY-MM-DD");
      }
      if (date.split(" ").length === 2) {
        this.$message.warning("最小为小时力度");
        return;
      }
      const result = await this.$fetchGet(
        `/power/getSupplyPowerDtoByDateTypeInfo/${dateType}/${dates}/${
          this.leftData[this.leftIndex].code
        }/${code.toUpperCase()}`
      );
      console.log(result);
      const arr1 = [];
      result.result.forEach(item => {
        Object.keys(item).forEach(key => {
          if (item[key]) {
            if (
              key === "year" ||
              key === "createTimeU" ||
              key === "supplyTableEnum" ||
              key === "month"
            ) {
              return;
            }
            arr1.push({
              name: item.createTimeU,
              value: item[key],
              code: key
            });
          }
        });
      });
      this.bottomOneChart.dispose();
      this.bottomOneChart = echarts.init(this.$refs["oneBottomChart"]);
      this.bottomOneChart.setOption(
        this.bottomOption(`2020年供能侧分析`, arr1)
      );
      this.bottomOneChart.on("click", params => {
        console.log(code)
        this.getBottomData(code, params.name);
      });
    },
    topOption(name, data) {
      return {
        title: {
          text: name,
          left: "left",
          top: 20,
          left: 50
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          type: "scroll",
          orient: "vertical",
          right: 10,
          top: 20,
          bottom: 20
        },
        color: ["#2994DF", "#9252B0", "#C79D43", "#24B9D2"],
        series: [
          {
            name: name,
            type: "pie",
            radius: "55%",
            center: ["40%", "50%"],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            },
            data: data.map(item => {
              return {
                value: item.value / 1000,
                name: item.name
              }
            })
          }
        ]
      };
    },
    bottomOption(name, data) {
      return {
        title: {
          text: name,
          left: "left",
          top: 20
        },
        toolbox: {
          feature: {
            dataView: {show: true, readOnly: false},
            magicType: {show: true, type: ['line', 'bar']},
            restore: {show: true},
            saveAsImage: {show: true}
          }
        },
        color: ["#3398DB"],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        xAxis: [
          {
            type: "category",
            data: data.map(item => item.name),
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: "value"
          }
        ],
        series: [
          {
            name: name,
            type: "bar",
            barWidth: "60%",
            data: data.map(item => item.value / 1000)
          }
        ]
      };
    },
    drawBottomOneChart() {
      this.bottomOneChart = echarts.init(this.$refs["oneBottomChart"]);
      this.bottomOneChart.setOption(
        // 【冷水】月能耗分析
        this.bottomOption(`2020年供能侧分析`, this.topOne)
      );
    },
    leftClick(index) {
      this.leftIndex = index;
      // this.bottomOneChart = null;
      this.bottomOneChart.dispose();
      this.getBottomDataQuery();
    }
  }
};
</script>

<style lang="less">
.analysis3-container {
  height: calc(100vh - 60px);
  .left-container {
    width: 200px;
    overflow-y: auto;
    padding: 20px;
    .left-item {
      cursor: pointer;
      font-size: 20px;
      padding: 20px;
      border-bottom: 1px solid #888;
      &.active {
        color: #f00;
      }
    }
  }
  display: flex;
  .right-container {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
  .query-container {
    margin-top: 20px;
    padding: 0 30px;
    text-align: right;
  }
  .top-container {
    flex: 1;
    display: flex;
    & > div {
      flex: 1;
      margin: 25px;
      border: 2px solid #efefef;
      box-sizing: border-box;
      display: flex;
    }
  }
  .bottom-container {
    flex: 1;
    display: flex;
    & > div {
      flex: 1;
      margin: 25px;
      border: 2px solid #efefef;
      box-sizing: border-box;
      display: flex;
    }
  }
}
</style>